package com.lizemin.listener;

import com.lizemin.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lzm
 * @date 2025/4/6 10:48
 * @description 会话管理监听器
 */
@Component
@Slf4j
public class SessionManagementListener implements HttpSessionListener {

    /**
     * 存储所有会话信息
     */
    private static final ConcurrentHashMap<String, HttpSession> SESSION_MAP = new ConcurrentHashMap<>();

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        log.info("会话已创建.....");
        HttpSession session = se.getSession();
        SESSION_MAP.put(session.getId(), session);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        log.info("会话已销毁.....");
        HttpSession session = se.getSession();
        SESSION_MAP.remove(session.getId());
    }

    /**
     * 获取所有会话信息
     */
    public List<HttpSession> getAllSessions() {
        ArrayList<HttpSession> sessions = new ArrayList<>(SESSION_MAP.values());
        // 过滤掉未登录的session
        sessions.removeIf(session -> Objects.isNull(session.getAttribute(Constants.LOGIN_STATUS)));
        return sessions;
    }

    /**
     * 获取当前活跃的会话数量
     *
     * @return 当前活跃的会话数量
     */
    public int getActiveSessionCount() {
        return SESSION_MAP.size();
    }

    /**
     * 移除指定的session
     *
     * @param sessionId sessionId
     */
    public void removeSession(String sessionId) {
        HttpSession session = SESSION_MAP.get(sessionId);
        if (Objects.isNull(session)) {
            log.info("sessionId为{}的session不存在", sessionId);
            return;
        }
        session.invalidate();
    }

    /**
     * 刷新sessionId
     * @param oldSessionId 旧的sessionId
     * @param newSessionId 新的sessionId
     */
    public void refreshSession(String oldSessionId, String newSessionId) {
        HttpSession session = SESSION_MAP.get(oldSessionId);
        if (Objects.isNull(session)) {
            log.info("sessionId为{}的session不存在, 无需处理", oldSessionId);
            return;
        }
        SESSION_MAP.put(newSessionId, session);
        SESSION_MAP.remove(oldSessionId);
    }
}
